package edu.fdzc.springboot01.controller;

import edu.fdzc.springboot01.entity.Department;
import edu.fdzc.springboot01.service.DepartmentService;
import edu.fdzc.springboot01.utils.ResultUtil;
import edu.fdzc.springboot01.vo.DeptVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/departments")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @GetMapping
    public Object getAllDepartments() {
        List<Department> departments = departmentService.list();
        return ResultUtil.success(departments);
    }

    @GetMapping("/{id}")
    public Object getDepartmentById(@PathVariable Integer id) {
        Department department = departmentService.getById(id);
        return ResultUtil.success(department);
    }

    @GetMapping("/{id}/with-users")
    public Object getDeptWithUsers(@PathVariable Integer id) {
        DeptVo deptVo = departmentService.getByIdWithUsers(id);
        return ResultUtil.success(deptVo);
    }

    @PostMapping
    public Object addDepartment(@RequestBody Department department) {
        boolean success = departmentService.save(department);
        return success ? ResultUtil.success() : ResultUtil.fail();
    }

    @PutMapping("/{id}")
    public Object updateDepartment(@PathVariable Integer id, @RequestBody Department department) {
        department.setId(id);
        boolean success = departmentService.updateById(department);
        return success ? ResultUtil.success() : ResultUtil.fail();
    }

    @DeleteMapping("/{id}")
    public Object deleteDepartment(@PathVariable Integer id) {
        boolean success = departmentService.removeById(id);
        return success ? ResultUtil.success() : ResultUtil.fail();
    }
}